<template>
    <div class="container">
        <top-nav :toLastPath="true">置顶支付</top-nav>
        <div class="limit">
            <div>置顶时间期限</div>
            <div @click.stop="showPicker" class="int">
                <input type="text"   readonly placeholder="选择时间期限" v-model="date">
                <span>></span>
            </div>
            <popup-picker ref="picker" :col="topType" @getSelectValue='getHours'></popup-picker>
        </div>
        <div class="content">
            <div class="play_type">
                <div>选择支付方式</div>
                <!-- v-for="(value,index) of initalData" :key="index" -->
                <div >
                   <div class="play_type_child">
                        <input type="radio" name="play_type" value="wechat" class="play_type_input" id="wechat"><label for="wechat">微信支付</label>
                   </div>
                    <div class="play_type_child">
                        <input type="radio" name="play_type" value="integral" class="play_type_input" id="integral"><label for="integral">积分支付</label>
                    </div>
                </div>
            </div>
        </div>
        <div class="footer">
            <div class="time">
                <span>置顶时间:</span>
                <span>{{today}}</span>
                <span  v-if="today!=''">-</span>
                <span>{{delayDate}}</span>
            </div>
            <div class="total">
                <div>合计：</div>
                <div v-if="price!=''"><span>￥</span>{{price}}<span>元</span></div>
                <div @click="pay">支付</div>
            </div>
        </div>
    </div>
</template>
<script>
    import topNav from '@/components/topNav'; 
    import popupPicker from '@/components/popupPicker';
    import { Dialog } from 'vant';
    import wx from 'weixin-js-sdk';
    export default{
        name:'setTop',
        data(){return{
            id:'',
            topType:[],
            date:'',
            initalData:'',
            // totalMoney:'',
            price:'',
            priceId:'',
            payType:'',
            today:'',
            delayDate:'',
            type:'',
        }},
        components:{
            topNav,
            popupPicker
        },
        mounted() {
            this.$nextTick(function () {
                this.getConfig()
            })
        },
        methods:{
            // 微信分参数
            async getConfig() {
                let url = location.href.split('#')[0] //获取锚点之前的链接
                let response=await this.$axios.post('https://wx.zhaowea.com/api/wx/getJsApiPacket',{url:url});
                let res = response.data.data;
                this.wxInit(res);
            },
            // 微信分享
            wxInit(res) {
                wx.config({
                    debug: false,
                    appId: res.appId,
                    timestamp: res.timestamp,
                    nonceStr: res.nonceStr,
                    signature: res.signature,
                    jsApiList: ['chooseWXPay']
                });
            },

            async getTop(){
                let res=await this.$axios.get('https://wx.zhaowea.com/api/position/setTopRule');
                if(res.data.level=='success'){
                    this.topType=[];
                    this.initalData=res.data.data;
                    res.data.data.forEach((val)=>{
                        this.topType.push(`${val.hours}小时`)

                    })
                }
                
            },
            showPicker(){
            this.$refs.picker.$data.showArea=true;
            },
            getHours(e){
                let pattern=/\d*/;
                let hour=pattern.exec(e)
                this.initalData.forEach((val)=>{
                    if(val.hours==hour){
                        this.priceId=val.id
                        this.price=val.num;
                    }
                })
                this.date=e;
                this.toDate()
            },
            toDate(){//获取日期
                let myDate = new Date()
                let year=myDate.getFullYear();
                let month=myDate.getMonth()+1;
                let date=myDate.getDate();
                this.today=`${year}-${month}-${date}`;
                let pattern=/\d*/;
                let hour=pattern.exec(this.date)
                let delay=hour/24;
                //获取延后日期;
                myDate.setDate(myDate.getDate()+delay)
                let year1=myDate.getFullYear();
                let month1=myDate.getMonth()+1;
                let date1=myDate.getDate();
                this.delayDate=`${year1}-${month1}-${date1}`;
                // console.log(str,str1)
                // var now = new Date();
                //     now.setDate(now.getDate()+1);  
                //     console.log(now);

            },
            async pay(){
                let userToken = window.localStorage.getItem('userToken')
                let fath = document.getElementsByClassName('play_type_input')
                for (let length = fath.length, i = 0; i < length; i++) {
                    if (fath[i].checked == true) {
                        this.payType = fath[i].value;
                        break
                    }
                }//判断是否是用微信支付
                if (this.date == '') {
                    this.$currency.showToast('置顶时间不能为空', '1500', 'fail')
                    return
                }
                if (this.payType == '') {
                    this.$currency.showToast('支付方式不能为空', '1500', 'fail')
                    return
                }
                let payType = '';
                payType = this.payType == 'wechat' ? 'wechat' : '';
                let res = await this.$axios.post('/order/buildOrder', {
                    rule_id: this.priceId,
                    user_token: userToken,
                    position_id: this.id,
                    type: payType,
                    advent_type:this.type
                });
                if (res.data.level != 'success') {
                    this.$currency.showToast(res.data.message, '1500', 'fail');
                } else {
                    Dialog.confirm({
                        title: '确认支付',
                    }).then(async() => {
                        this.order_num = res.data.data.order_num;
                        let resPay = await this.$axios.post('/payment/wechatAppPay', {
                            order_num: this.order_num,
                            user_token: userToken,
                            pay_type: 'wx'
                        });

//                        var jsConfig = "";
//                        var url=location.href;
//                        let jsPacket = await this.$axios.get('/wx/getJsApiPacket',{params:{url:url}});
//                        if(jsPacket.data.level == "success"){
//                            jsConfig = jsPacket.data.data;
//                        }
                        if (resPay.data.level == "success") {
                            this.WXPayment(resPay.data.data);
                        }
                    }).catch((e) => {
                        // console.log(e);
                    });
                }
            },
                WXPayment(data)
                {
                    var _this = this;
                    if (typeof WeixinJSBridge === 'undefined') {
                        _this.$currency.showToast('请在微信在打开页面', '1500', 'fail');
                        return false;
                    }
                    // console.log(data);
                    var aa = data.timestamp;
                    // console.log(aa);
//                    wx.chooseWXPay({
//                        timestamp:data.timestamp,
//                        nonceStr: data.nonceStr,
//                        package: data.package,
//                        signType: 'MD5',
//                        paySign: data.paySign,
//                        success: function (res) {
//                            _this.$currency.showToast('支付成功', '1500', 'fail')
//                        },
//                        fail:function (res) {
//                            alert(res);
//                        }
//                    });
                    WeixinJSBridge.invoke('getBrandWCPayRequest', data, function (res) {
                        switch (res.err_msg) {
                            case 'get_brand_wcpay_request:cancel':
                                _this.$currency.showToast('用户取消支付！', '1500', 'fail');
                                break;
                            case 'get_brand_wcpay_request:fail':
                                _this.$currency.showToast('支付失败！(' + res.err_desc + ')', '1500', 'fail')
                                break;
                            case 'get_brand_wcpay_request:ok':
                                _this.$currency.showToast('支付成功,正在跳转', '1000', 'fail')
                                // window.location.href='{{route('Home.Page.joinMember')}}';
                                setTimeout(() => {
                                    if(_this.type=='position'){
                                        _this.$router.push({name:'people'})
                                    }else{
                                        _this.$router.push({name:'me'})
                                    }
                                }, 1500)
                                break;
                            default:
                                // alert(JSON.stringify(res));
                                break;
                        }
                    });
                }
            },

        activated() {
            this.id=this.$route.params.id;
            this.type = this.$store.state.modulesInvestment.adventType;
            console.log(this.type)
            this.getTop()
        },
    }
</script>
<style scoped>
    .container{
        height: 100vh;
        overflow: hidden;
        position: relative;
    }
    .limit{
        margin-left:10px;
        background-color: #fff;
        font-size: 18px;
        /* padding-top:45px; */
        margin-top: 45px;
        height: 50px;
        display: flex;
        align-items: center;
        border-bottom:1px solid #eee;
        }
    input{border:none;}
    .limit input{
        margin-left:15px;
    }
    .int{
        color:gray;
        font-size: 20px;
    }
    .int>input{
        width: 150px;
    }
    .int>span{
        margin-right: 10px;
    }
    .play_type>div:nth-child(1){
        text-align: center;
        font-size: 25px;
    }
    .play_type>div:nth-child(2){
        /* text-align: center; */
        font-size: 20px;
    }
    .play_type>div:nth-child(2){
        margin-top:50px;
        margin-left:10px;
    }
    .play_type_child{
        margin-top:10px;
    }
    .footer{
        border-top:1px solid #eee;
        position: absolute;
        bottom: 20px;
        width: 100%;
    }
    .time{
        font-size: 18px;
        color:gray;
        margin-left: 15px;
        height: 50px;
    }
    .total{
        margin-left: 15px;
        margin-top: 10px;
        width: 100%;
        overflow: hidden;
    }
    .total>div{
        float:left;
        font-size: 20px;
        line-height: 50px;
        height: 50px;
    }
    .total>div:last-child{
        float: right;
        color:#fff;
        margin-right: 20px;
        border-radius: 10px;
        padding:0 30px;
        background-image: linear-gradient(-135deg, #57D1E2 0%, #37AED6 100%);
    }
</style>